﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Qiao.Common.Core.反射
{
    /// <summary>
    /// 实体反射类
    /// 该类主要实现，通过传入一个实体，然后调用不同的方法，执行反射操作，得到不同的反射内容
    /// 可以通过调用 EntityQuerySql 实现通过反射的方式拿到一个 Select 语句
    /// </summary>
    public class EntityReflection
    {

        #region SQL
        /// <summary>
        /// 查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string EntityQuerySql<T>(T obj) where T : class, new()
        {
            string sql = "";

            return sql;
        }

        public static string EntityInsertSql<T>(T obj) where T : class, new()
        {
            string sql = "Insert Into {0} ({1}) VALUES ({2}) ";
            Type type = typeof(T);
            object objEntity = Activator.CreateInstance(type);
            string entityName = type.Name;
            string values = "";
            string valueNames = "";
            List<string> valueList = new List<string>();
            List<string> nameList = new List<string>();

            foreach (PropertyInfo item in type.GetProperties())
            {
                nameList.Add(item.Name);
                if (item.PropertyType.IsValueType)
                {
                    if (item.PropertyType.Name == "DateTime")
                    {
                        valueList.Add("'" + item.GetValue(obj).ToString() + "'");
                    }
                    else
                    {
                        valueList.Add(item.GetValue(obj).ToString());
                    }
                }
                else
                {
                    valueList.Add("'" + item.GetValue(obj).ToString() + "'");
                }
            }
            values = string.Join(",", valueList);
            valueNames = string.Join(",", nameList);

            return string.Format(sql, entityName, valueNames, values);
        }
        #endregion

    }
}
